package com.atom.module.author.service.impl;

import com.atom.module.author.mapper.AuthorMapper;
import com.atom.module.author.mapper.JointMapper;
import com.atom.module.author.pojo.entity.Author;
import com.atom.module.author.pojo.entity.Permission;
import com.atom.module.author.pojo.entity.Role;
import com.atom.module.author.security.LoginUser;
import com.atom.module.common.exception.ServiceException;
import com.atom.module.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AuthorMapper authorMapper;

    @Autowired
    private JointMapper jointMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Author author = authorMapper.selectByAccount(username);
        if (StringUtils.isNull(author)) {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException("user.not.exists");
        } else if (Boolean.TRUE.equals(author.getDeleted())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException("user.password.delete");
        } else if (Boolean.FALSE.equals(author.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException("user.blocked");
        }

        return new LoginUser(author) {
            @Override
            public List<Permission> providerPermission(Author author) {
                return jointMapper.selectPermission(author.getId());
            }

            @Override
            public List<Role> providerRole(Author author) {
                return jointMapper.selectRole(author.getId());
            }
        };
    }
}
